"""
简化版素材上传GUI界面

使用标准Tkinter + ttk创建现代化的素材上传界面
兼容性更好，无需额外依赖
"""

import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import os
import threading
from pathlib import Path
from typing import List, Optional
import hashlib
from PIL import Image, ImageTk


class SimpleUploadGUI:
    """简化版素材上传GUI"""
    
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("短视频混剪工具 - 素材上传")
        self.root.geometry("1000x700")
        self.root.minsize(800, 600)
        
        # 设置主题
        self.setup_theme()
        
        # 初始化变量
        self.selected_files = []
        self.current_product = tk.StringVar(value="请选择商品...")
        
        # 创建界面
        self.create_widgets()
    
    def setup_theme(self):
        """设置界面主题"""
        # 配置ttk样式
        style = ttk.Style()
        
        # 尝试使用现代主题
        available_themes = style.theme_names()
        if 'clam' in available_themes:
            style.theme_use('clam')
        elif 'alt' in available_themes:
            style.theme_use('alt')
        
        # 自定义样式
        style.configure('Title.TLabel', font=('Arial', 18, 'bold'))
        style.configure('Heading.TLabel', font=('Arial', 12, 'bold'))
        style.configure('Upload.TFrame', relief='solid', borderwidth=2)
        style.configure('Big.TButton', font=('Arial', 12, 'bold'))
    
    def create_widgets(self):
        """创建界面组件"""
        # 主容器
        main_frame = ttk.Frame(self.root, padding="20")
        main_frame.pack(fill="both", expand=True)
        
        # 创建各个区域
        self.create_header(main_frame)
        self.create_product_selection(main_frame)
        self.create_upload_area(main_frame)
        self.create_file_list(main_frame)
        self.create_control_buttons(main_frame)
        self.create_status_bar(main_frame)
    
    def create_header(self, parent):
        """创建标题区域"""
        header_frame = ttk.Frame(parent)
        header_frame.pack(fill="x", pady=(0, 20))
        
        # 标题
        title_label = ttk.Label(
            header_frame,
            text="📁 原始素材上传",
            style='Title.TLabel'
        )
        title_label.pack(side="left")
        
        # 帮助按钮
        help_button = ttk.Button(
            header_frame,
            text="❓ 帮助",
            command=self.show_help
        )
        help_button.pack(side="right")
    
    def create_product_selection(self, parent):
        """创建商品选择区域"""
        product_frame = ttk.LabelFrame(parent, text="商品选择", padding="10")
        product_frame.pack(fill="x", pady=(0, 20))
        
        # 商品选择
        ttk.Label(product_frame, text="选择商品:").pack(side="left", padx=(0, 10))
        
        self.product_combobox = ttk.Combobox(
            product_frame,
            textvariable=self.current_product,
            values=["请选择商品...", "商品A - SKU001", "商品B - SKU002", "商品C - SKU003"],
            width=30,
            state="readonly"
        )
        self.product_combobox.pack(side="left", padx=(0, 10))
        
        # 新建商品按钮
        new_product_button = ttk.Button(
            product_frame,
            text="+ 新建商品",
            command=self.create_new_product
        )
        new_product_button.pack(side="left")
    
    def create_upload_area(self, parent):
        """创建上传区域"""
        upload_frame = ttk.LabelFrame(parent, text="文件上传", padding="20")
        upload_frame.pack(fill="x", pady=(0, 20))
        
        # 上传区域
        self.drop_frame = ttk.Frame(upload_frame, style='Upload.TFrame', padding="40")
        self.drop_frame.pack(fill="x")
        
        # 上传图标和文字
        upload_label = ttk.Label(
            self.drop_frame,
            text="☁️ 点击选择文件或拖拽文件到此处",
            font=('Arial', 14, 'bold'),
            anchor="center"
        )
        upload_label.pack(pady=(0, 10))
        
        hint_label = ttk.Label(
            self.drop_frame,
            text="支持视频、图片、音频文件 (MP4, AVI, MOV, JPG, PNG, MP3, WAV)",
            font=('Arial', 10),
            anchor="center"
        )
        hint_label.pack(pady=(0, 15))
        
        # 选择文件按钮
        select_button = ttk.Button(
            self.drop_frame,
            text="📂 选择文件",
            style='Big.TButton',
            command=self.select_files
        )
        select_button.pack()
        
        # 绑定点击事件
        self.drop_frame.bind("<Button-1>", lambda e: self.select_files())
        upload_label.bind("<Button-1>", lambda e: self.select_files())
    
    def create_file_list(self, parent):
        """创建文件列表区域"""
        list_frame = ttk.LabelFrame(parent, text="待上传文件列表", padding="10")
        list_frame.pack(fill="both", expand=True, pady=(0, 20))
        
        # 创建Treeview
        columns = ('name', 'size', 'type', 'status')
        self.file_tree = ttk.Treeview(list_frame, columns=columns, show='headings', height=8)
        
        # 设置列标题
        self.file_tree.heading('name', text='文件名')
        self.file_tree.heading('size', text='大小')
        self.file_tree.heading('type', text='类型')
        self.file_tree.heading('status', text='状态')
        
        # 设置列宽
        self.file_tree.column('name', width=300)
        self.file_tree.column('size', width=100)
        self.file_tree.column('type', width=80)
        self.file_tree.column('status', width=100)
        
        # 滚动条
        scrollbar = ttk.Scrollbar(list_frame, orient="vertical", command=self.file_tree.yview)
        self.file_tree.configure(yscrollcommand=scrollbar.set)
        
        # 布局
        self.file_tree.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
        
        # 绑定右键菜单
        self.file_tree.bind("<Button-3>", self.show_context_menu)
    
    def create_control_buttons(self, parent):
        """创建控制按钮区域"""
        button_frame = ttk.Frame(parent)
        button_frame.pack(fill="x", pady=(0, 20))
        
        # 左侧按钮
        left_frame = ttk.Frame(button_frame)
        left_frame.pack(side="left")
        
        clear_button = ttk.Button(
            left_frame,
            text="🗑️ 清空列表",
            command=self.clear_file_list
        )
        clear_button.pack(side="left", padx=(0, 10))
        
        batch_button = ttk.Button(
            left_frame,
            text="⚙️ 批量设置",
            command=self.batch_settings
        )
        batch_button.pack(side="left")
        
        # 右侧按钮
        right_frame = ttk.Frame(button_frame)
        right_frame.pack(side="right")
        
        self.pause_button = ttk.Button(
            right_frame,
            text="⏸️ 暂停",
            command=self.pause_upload,
            state="disabled"
        )
        self.pause_button.pack(side="right", padx=(10, 0))
        
        self.upload_button = ttk.Button(
            right_frame,
            text="🚀 开始上传",
            style='Big.TButton',
            command=self.start_upload
        )
        self.upload_button.pack(side="right")
    
    def create_status_bar(self, parent):
        """创建状态栏"""
        status_frame = ttk.Frame(parent)
        status_frame.pack(fill="x")
        
        # 状态文本
        self.status_var = tk.StringVar(value="就绪")
        status_label = ttk.Label(status_frame, textvariable=self.status_var)
        status_label.pack(side="left")
        
        # 进度条
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(
            status_frame,
            variable=self.progress_var,
            maximum=100,
            length=300
        )
        self.progress_bar.pack(side="right")
    
    def select_files(self):
        """选择文件"""
        file_types = [
            ("所有支持的文件", "*.mp4 *.avi *.mov *.mkv *.jpg *.jpeg *.png *.gif *.mp3 *.wav *.m4a"),
            ("视频文件", "*.mp4 *.avi *.mov *.mkv"),
            ("图片文件", "*.jpg *.jpeg *.png *.gif"),
            ("音频文件", "*.mp3 *.wav *.m4a"),
            ("所有文件", "*.*")
        ]
        
        files = filedialog.askopenfilenames(
            title="选择素材文件",
            filetypes=file_types
        )
        
        if files:
            self.add_files(files)
    
    def add_files(self, file_paths: List[str]):
        """添加文件到列表"""
        for file_path in file_paths:
            if file_path not in [f['path'] for f in self.selected_files]:
                file_info = self.get_file_info(file_path)
                self.selected_files.append(file_info)
        
        self.update_file_list()
        self.update_status()
    
    def get_file_info(self, file_path: str) -> dict:
        """获取文件信息"""
        file_path = Path(file_path)
        file_size = file_path.stat().st_size
        
        return {
            'path': str(file_path),
            'name': file_path.name,
            'size': file_size,
            'type': self.get_file_type(file_path.suffix),
            'status': '待上传'
        }
    
    def get_file_type(self, extension: str) -> str:
        """根据扩展名获取文件类型"""
        video_exts = ['.mp4', '.avi', '.mov', '.mkv', '.wmv']
        image_exts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp']
        audio_exts = ['.mp3', '.wav', '.m4a', '.aac']
        
        ext = extension.lower()
        if ext in video_exts:
            return '视频'
        elif ext in image_exts:
            return '图片'
        elif ext in audio_exts:
            return '音频'
        else:
            return '其他'
    
    def update_file_list(self):
        """更新文件列表显示"""
        # 清空现有列表
        for item in self.file_tree.get_children():
            self.file_tree.delete(item)
        
        # 添加文件
        for file_info in self.selected_files:
            size_text = self.format_file_size(file_info['size'])
            self.file_tree.insert('', 'end', values=(
                file_info['name'],
                size_text,
                file_info['type'],
                file_info['status']
            ))
    
    def format_file_size(self, size_bytes: int) -> str:
        """格式化文件大小"""
        if size_bytes == 0:
            return "0 B"
        
        size_names = ["B", "KB", "MB", "GB"]
        i = 0
        size = float(size_bytes)
        
        while size >= 1024.0 and i < len(size_names) - 1:
            size /= 1024.0
            i += 1
        
        return f"{size:.1f} {size_names[i]}"
    
    def show_context_menu(self, event):
        """显示右键菜单"""
        item = self.file_tree.selection()[0] if self.file_tree.selection() else None
        if item:
            menu = tk.Menu(self.root, tearoff=0)
            menu.add_command(label="删除", command=lambda: self.remove_selected_file())
            menu.add_command(label="查看详情", command=lambda: self.show_file_details())
            menu.tk_popup(event.x_root, event.y_root)
    
    def remove_selected_file(self):
        """删除选中的文件"""
        selection = self.file_tree.selection()
        if selection:
            item = selection[0]
            index = self.file_tree.index(item)
            if 0 <= index < len(self.selected_files):
                self.selected_files.pop(index)
                self.update_file_list()
                self.update_status()
    
    def show_file_details(self):
        """显示文件详情"""
        selection = self.file_tree.selection()
        if selection:
            item = selection[0]
            index = self.file_tree.index(item)
            if 0 <= index < len(self.selected_files):
                file_info = self.selected_files[index]
                details = f"""
文件详情:

文件名: {file_info['name']}
路径: {file_info['path']}
大小: {self.format_file_size(file_info['size'])}
类型: {file_info['type']}
状态: {file_info['status']}
                """
                messagebox.showinfo("文件详情", details.strip())
    
    def clear_file_list(self):
        """清空文件列表"""
        if self.selected_files:
            result = messagebox.askyesno("确认", "确定要清空所有文件吗？")
            if result:
                self.selected_files.clear()
                self.update_file_list()
                self.update_status()
    
    def update_status(self):
        """更新状态"""
        file_count = len(self.selected_files)
        total_size = sum(f['size'] for f in self.selected_files)
        size_text = self.format_file_size(total_size)
        
        if file_count == 0:
            self.status_var.set("就绪")
        else:
            self.status_var.set(f"已选择 {file_count} 个文件，总大小 {size_text}")
    
    def create_new_product(self):
        """创建新商品"""
        messagebox.showinfo("提示", "新商品创建功能开发中...")
    
    def batch_settings(self):
        """批量设置"""
        messagebox.showinfo("提示", "批量设置功能开发中...")
    
    def start_upload(self):
        """开始上传"""
        if self.current_product.get() == "请选择商品...":
            messagebox.showwarning("警告", "请先选择商品！")
            return
        
        if not self.selected_files:
            messagebox.showwarning("警告", "请先选择要上传的文件！")
            return
        
        # 开始上传
        self.upload_button.configure(state="disabled")
        self.pause_button.configure(state="normal")
        
        # 在新线程中执行上传
        upload_thread = threading.Thread(target=self.upload_files)
        upload_thread.daemon = True
        upload_thread.start()
    
    def upload_files(self):
        """上传文件（模拟）"""
        total_files = len(self.selected_files)
        
        for i, file_info in enumerate(self.selected_files):
            # 更新状态
            file_info['status'] = '上传中'
            self.root.after(0, self.update_file_list)
            
            # 模拟上传进度
            for progress in range(0, 101, 20):
                self.root.after(0, lambda p=progress: self.progress_var.set(p))
                threading.Event().wait(0.2)
            
            # 完成上传
            file_info['status'] = '已完成'
            self.root.after(0, self.update_file_list)
            
            # 更新总进度
            overall_progress = ((i + 1) / total_files) * 100
            self.root.after(0, lambda p=overall_progress: self.progress_var.set(p))
        
        # 上传完成
        self.root.after(0, self.upload_completed)
    
    def upload_completed(self):
        """上传完成"""
        self.upload_button.configure(state="normal")
        self.pause_button.configure(state="disabled")
        self.status_var.set("上传完成！")
        messagebox.showinfo("成功", "所有文件上传完成！")
    
    def pause_upload(self):
        """暂停上传"""
        messagebox.showinfo("提示", "暂停上传功能开发中...")
    
    def show_help(self):
        """显示帮助"""
        help_text = """
素材上传帮助：

1. 首先选择要上传素材的商品
2. 点击"选择文件"选择要上传的文件
3. 支持的文件格式：
   - 视频：MP4, AVI, MOV, MKV
   - 图片：JPG, PNG, GIF
   - 音频：MP3, WAV, M4A
4. 在文件列表中可以右键删除不需要的文件
5. 点击"开始上传"进行批量上传

注意：请确保文件大小不超过500MB
        """
        messagebox.showinfo("帮助", help_text)
    
    def run(self):
        """运行GUI"""
        self.root.mainloop()


def main():
    """主函数"""
    app = SimpleUploadGUI()
    app.run()


if __name__ == "__main__":
    main()
